package com.gict.antifraudback.utils.oss;

import com.gict.antifraudback.config.COSConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectTagging;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.SetObjectTaggingRequest;
import com.qcloud.cos.model.Tag.Tag;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 腾讯oss存储服务
 */
@Service
public class TencentOssUtil {

    private final COSConfig cosConfig;
    private final COSClient cosClient;

    @Autowired
    public TencentOssUtil(COSConfig cosConfig) {
        this.cosConfig = cosConfig;
        this.cosClient = createCli();
    }

    // 上传文件到 COS
    public Map<String, String> uploadFileToCOS(MultipartFile multipartFile, String fileName) {
        Map<String, String> result = new HashMap<>();
        File file = null;
        try {
            file = convertMultipartFileToFile(multipartFile);
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), fileName, file);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            System.out.println("文件上传成功，ETag: " + putObjectResult.getETag());
            result.put("ETag", putObjectResult.getETag());
            result.put("requestId", putObjectRequest.getKey());
            result.put("url", cosConfig.getPrefix() + fileName);
        } catch (CosClientException | IOException e) {
            System.err.println("文件上传失败: " + e.getMessage());
        } finally {
            if (file != null && file.exists()) {
                file.delete();
            }
        }
        return result;
    }

    // 设置对象标签
    public void setObjectTags(String fileName) {
        List<Tag> tags = new ArrayList<>();
        tags.add(new Tag("category", "article"));
        SetObjectTaggingRequest setObjectTaggingRequest = new SetObjectTaggingRequest(cosConfig.getBucketName(), fileName, new ObjectTagging(tags));
        cosClient.setObjectTagging(setObjectTaggingRequest);
        System.out.println("标签已成功设置！");
    }

    // 创建 COSClient
    private COSClient createCli() {
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegionName()));
        return new COSClient(cred, clientConfig);
    }

    // 辅助方法：将 MultipartFile 转换为 File
    private File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        File convFile = File.createTempFile("upload-", ".tmp");
        try (FileOutputStream fos = new FileOutputStream(convFile)) {
            fos.write(multipartFile.getBytes());
        }
        return convFile;
    }

    public Map<String, String> putLocalFile(String fileName, File file) {
        Map<String, String> result = new HashMap<>();
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), fileName, file);
        try {
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            System.out.println("文件上传成功，ETag: " + putObjectResult.getETag());
            System.out.printf("访问路径%s%n", cosConfig.getPrefix() + fileName);
            result.put("ETag", putObjectResult.getETag());
            result.put("requestId", putObjectRequest.getKey());
            result.put("url", cosConfig.getPrefix() + fileName);
            setObjectTags(fileName);
        } catch (CosClientException e) {
            System.out.println("文件上传失败");
        }

        return result;
    }
}
